import axios from 'axios'
import qs from 'qs'

const toHash = (params) => { // 传参转码
  var obj = {}
  for (var i in params) {
    obj[i] = encodeURIComponent(params[i])
  }
  return obj
}

const get = (url, params, boolean) => {
  return new Promise((resolve, reject) => {
    if (boolean === null || boolean === '' || boolean === undefined) {
      boolean = false
    }
    axios.get(url, {params: boolean === false ? params : toHash(params)}).then(res => {
      resolve(res.data)
    }).catch(err => {
      reject(err)
    })
  })
}

const post = (url, params, boolean) => {
  return new Promise((resolve, reject) => {
    if (boolean === null || boolean === '' || boolean === undefined) {
      boolean = false
    }
    axios.post(url, qs.stringify(boolean === false ? params : toHash(params))).then(res => {
      resolve(res.data)
    }).catch(err => {
      reject(err)
    })
  })
}

const postFile = (url, params, boolean) => {
  return new Promise((resolve, reject) => {
    if (boolean === null || boolean === '' || boolean === undefined) {
      boolean = false
    }
    axios.post(url, boolean === false ? params : toHash(params), {header: {'Content-Type': 'multipart/form-data'}}).then(res => {
      resolve(res.data)
    }).catch(err => {
      reject(err)
      this.$Message.error({content: '网络异常', duration: 5})
    })
  })
}

export default {
  get, post, postFile
}
